package com.icinfo.cloud.provider.punish.common.client.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.punish.common.client.IUserCenterClient;
import com.icinfo.cloud.provider.punish.common.client.dto.PunishListPageDto;
import com.icinfo.cloud.provider.punish.common.client.vo.PunishListPageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检查-usercenter client接口类
 *
 * @author Junfeng.Chen
 * @date 2024/2/6 10:11
 **/
@Slf4j
@Component
public class UserCenterClient implements IUserCenterClient {
    /**
     * userCenter项目 请求路径前缀
     */
    @Value("${member.url}")
    private String url;

    /**
     * 获取事项catalogId通过busId 接口路径
     */
    @Value("${member.api.getCatalogIdByBusId}")
    private String getCatalogIdByBusIdApi;

    /**
     * 分页获取事项列表
     */
    @Value("${member.api.getPunishListInfo}")
    private String getPunishListInfo;

    /**
     * 通过catalogId获取事项适用类型
     */
    @Value("${member.api.getPunishTypeByCatalogId}")
    private String getPunishTypeByCatalogId;

    public String getCatalogIdByBusIdApi() {
        return url + getCatalogIdByBusIdApi;
    }

    @Override
    public String getCatalogIdByBusId(String busId) {
        Map<String, String> params = new HashMap<>();
        params.put("busId", busId);
        return httpGet(getCatalogIdByBusIdApi, params);
    }

    @Override
    public PageResponse<PunishListPageVo> getPunishListInfo(PunishListPageDto dto) {
        String data = httpPost(getPunishListInfo, dto);
        //由于检查的PageResponse与我们的不同，所以需要转换下total
        JSONObject result = JSONObject.parseObject(data);
        Long total = result.getLong("total");
        PageResponse<PunishListPageVo> pageResponse = JSON.parseObject(data, new TypeReference<PageResponse<PunishListPageVo>>() {
        });
        pageResponse.setRecordsTotal(total);
        return pageResponse;
    }

    @Override
    public List<String> getPunishTypeByCatalogId(String catalogId) {
        Map<String, String> params = new HashMap<>();
        params.put("catalogId", catalogId);
        String data = httpGet(getPunishTypeByCatalogId, params);
        log.info("getPunishTypeByCatalogId返回：{}", data);
        return JSONArray.parseArray(data, String.class);
    }

    /**
     * get请求
     *
     * @param api    api相对路径
     * @param params 参数
     * @return 响应结果 data字段数据
     */
    private String httpGet(String api, Object params) {
        Map<String, String> headers = HeaderUtil.authHeader();
        //发起get请求
        String resultBody = "";
        try (HttpResponse response = HttpUtil.createGet(assemblyApi(api))
                .addHeaders(headers).form(JSONObject.parseObject(JSON.toJSONString(params)))
                .execute()) {
            resultBody = response.body();
        }
        return getResponseData(resultBody);
    }

    private String httpPost(String api, Object params) {
        Map<String, String> headers = HeaderUtil.authHeader();
        //发起get请求
        String resultBody = "";
        try (HttpResponse response = HttpUtil.createPost(assemblyApi(api))
                .addHeaders(headers).body(JSON.toJSONString(BeanUtil.beanToMap(params)))
                .execute()) {
            resultBody = response.body();
        }
        return getResponseData(resultBody);
    }

    /**
     * 获取响应data
     *
     * @param resultBody 响应body
     * @return
     */
    private String getResponseData(String resultBody) {
        JSONObject response = JSON.parseObject(resultBody);
        if (HttpStatus.HTTP_OK != response.getInteger("code")) {
            throw new BusinessException(response.getString("message"));
        }
        return response.getString("data");
    }


    /**
     * 组装api完整路径
     *
     * @param api 接口相对路径
     * @return 完整api路径
     */
    private String assemblyApi(String api) {
        return url + api;
    }
}
